package com.cssy.xxkj.logic.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONArray;
import com.cssy.authority.dao.AppSqlConfig;
import com.cssy.authority.service.IAuthorityService;
import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.authority.service.impl.AuthorityServiceImpl;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.entity.BasicCompanyTestDO;
import com.cssy.xxkj.basic.entity.BasicMaterialsTypeDO;
import com.cssy.xxkj.basic.entity.BasicStorageInfoTestDO;
import com.cssy.xxkj.basic.service.IBasicUtilService;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.entity.LogicPurchaseDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseItemDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseWareDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseWareItemDO;
import com.cssy.xxkj.logic.service.ILogicPurchaseItemService;
import com.cssy.xxkj.logic.service.ILogicPurchaseWareItemService;
import com.cssy.xxkj.logic.service.ILogicPurchaseWareService;
import com.cssy.xxkj.logic.service.ILogicUtilService;
import com.cssy.xxkj.logic.util.OftenMapUtil;
import com.cssy.xxkj.logic.util.OftenMothedUtil;
import com.cssy.yd.logic.util.SqlUtil;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;

/**
 * 采购(原材料/成品)入库单
 * @author zeyong.gui
 *
 */

@Controller
@RequestMapping("/logic/purchaseware")
public class PurchaseWareController extends BaseController<LogicPurchaseWareDO> {
	
	private static final String MANAGER = "/xxkj/logic/purchaseware/PurchaseWareManager";
	private static final String EIDT = "/xxkj/logic/purchaseware/PurchaseWareOperation";
	
	@Resource(name = "basicUtilService")
	IBasicUtilService basicUtilService;
	
	@Resource(name = "logicUtilService")
	ILogicUtilService logicUtilService;
	
	@Resource(name = "logicPurchaseWareService")
	ILogicPurchaseWareService logicPurchaseWareService;
	
	@Resource(name = "logicPurchaseItemService")
	ILogicPurchaseItemService logicPurchaseItemService;
	
	@Resource(name = "logicPurchaseWareItemService")
	ILogicPurchaseWareItemService logicPurchaseWareItemService;
	
	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;
	
	@Resource(name = "oftenMothedUtil")
	private OftenMothedUtil oftenMothedUtil;
	
	@Resource(name = "oftenMapUtil")
	private OftenMapUtil oftenMapUtil;
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		/*JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs.setRemovedProperty("removed");
		List<BasicStorageInfoTestDO> list = basicUtilService.resultStorage(scs);
		model.addAttribute("wh",list);*/
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs=this.oftenMothedUtil.getNoFinishConditions(scs, "zd004Status", BillStatusUtil.PCSW_BILL_STATUS_FOUR);
		if(StringUtils.isBlank(scs.getOrderBy())){
			scs.setOrderBy(" zd013Date desc, zd003Code desc");
		}
		Map<String, Object> whMap = SqlUtil.sqlUtil.roleWhSqlFilter(request, scUserRolePlaceService, "zd006WhCode");
		scs.addCondition(whMap.get("option")+"",(List<String>)whMap.get("roleWhList"));
		SearchResult result = logicPurchaseWareService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}

	@Override
	public String operationForm(HttpServletRequest request, @PathVariable String id,
			@PathVariable String flag, Model model) throws Exception {
		if (OperationFlag.ADD.equals(flag)) {
			model.addAttribute("bizCreatorName", SessionUtil.getUser(request).getRealName());
			model.addAttribute("flag", "ADD");
		} else {
			LogicPurchaseWareDO purchaseware = logicPurchaseWareService.findListById(id);
			model.addAttribute("pcsware", purchaseware);
			if(purchaseware!=null&&StringUtils.isNotBlank(purchaseware.getBizCreatorName())){
				SqlMapClient sqlMapClient = AppSqlConfig.getSqlMapInstance();
				IAuthorityService ias = new AuthorityServiceImpl(sqlMapClient);
				com.cssy.authority.entity.User u = ias.getByUserName(purchaseware.getBizCreatorName());
				model.addAttribute("userName", u.getRealname());
			}
		}
		//仓库记录
		SearchConditions sgfScs = new SearchConditions();
		sgfScs.setRemovedProperty(null);
		List<BasicStorageInfoTestDO> sgfList = basicUtilService.resultStorage(sgfScs);
		model.addAttribute("sgfList", sgfList);
		//查询采购订单
		SearchConditions pcsScs = new SearchConditions();
		pcsScs.setRemovedProperty(null);
		List<LogicPurchaseDO> pcsList = logicUtilService.resultPurchase(pcsScs);
		model.addAttribute("pcsList", pcsList);
		
		
		return EIDT;
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicPurchaseWareDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try{
			String itemdata = request.getParameter("itemdata");
			if(StringUtils.isBlank(itemdata)){
				bodyMap.isFail();
				bodyMap.configWebInfor("产品列表不能为空！");
				return bodyMap.modelMap;
			}
			/*if(StringUtils.isBlank(curAP.getZd022PiCode())){
				bodyMap.isFail();
				bodyMap.configWebInfor("PI编号不能为空！");
				return bodyMap.modelMap;
			}*/
			logicPurchaseWareService.purchaseWareSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		}catch(Exception e){
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()+ e.getMessage());

		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				if(StringUtils.isBlank(field)){
					continue;
				}else{
					logicPurchaseWareService.deleteBizRemoved(field);
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	/**
	 * 根据供应商ID取得供应商
	 * @param response
	 * @param gysCode
	 */
	@RequestMapping("/getGysInfo")
	public void getGysInfo(HttpServletResponse response,@RequestParam("supeId") String supeId){
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);
		scs.addCondition("id",supeId,SearchCondition.OP_EQUAL);
		List<BasicCompanyTestDO> bc = basicUtilService.resultCompany(scs);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("spGys", bc.get(0));
		AjaxUtil.printJSonArr(response, JSONArray.toJSONString(map));
	}
	
	/**
	 * 查询采购入库单的行记录
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/gridItems")
	public void gridItems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicPurchaseWareDO purchaseWare = logicPurchaseWareService.findListById(id);
			SearchConditions scs = new SearchConditions();
			scs.setRemovedProperty(null);//判断是否有删除标识
			if(purchaseWare!=null && StringUtils.isNotBlank(purchaseWare.getId())){
				scs.addCondition("zd001PusWareId", purchaseWare.getId(), SearchCondition.OP_EQUAL);
			}
			List<LogicPurchaseWareItemDO> pusWareItemList = logicPurchaseWareItemService.findListByExample(scs).getResults();
			OutJsonGrid out = new OutJsonGrid(pusWareItemList);
			out.printJSon(response);
		}
	}

	/**
	 * 根据采购单号查询采购订单的行记录(purchaseItem)信息
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/pcsItems")
	public void pcsItems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String pcsId = request.getParameter("pcsId");
		if(StringUtils.isNotBlank(pcsId)){
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("pcsId", pcsId);
			List<LogicPurchaseItemDO> pcsmList = logicPurchaseItemService.findListByMap(paramMap);
			if(pcsmList==null||pcsmList.isEmpty()||pcsmList.size()==0){
				return;
			}else{
				List<LogicPurchaseWareItemDO> pcswmList = new ArrayList<LogicPurchaseWareItemDO>();
				Map<String, BigDecimal> hasInMap = new HashMap<String, BigDecimal>();
				Map<String, Object> pcswmMap = new HashMap<String, Object>();
				pcswmMap.put("pcsId", pcsId);
				pcswmMap.put("zdStatus", BillStatusUtil.PCSW_BILL_STATUS_FOUR);
				List<LogicPurchaseWareItemDO> pcsmExList = logicPurchaseWareItemService.findListByMap(pcswmMap);
				if(pcsmExList!=null&&!pcsmExList.isEmpty()&&pcsmExList.size()>0){
					for(LogicPurchaseWareItemDO pcswmEx : pcsmExList){
						if(pcswmEx==null){
							continue;
						}
						BigDecimal hsQuantity = pcswmEx.getZd018HsQuantity()==null?BigDecimal.ZERO:pcswmEx.getZd018HsQuantity();
						String keyStr = pcswmEx.getZd003MaterId()+"_"+pcswmEx.getZd007Model()+"_"+pcswmEx.getZd011Size()+"_"
								+pcswmEx.getZd009Color()+"_"+pcswmEx.getZd010Quality();
						if(hasInMap.get(keyStr)==null){
							hasInMap.put(keyStr, hsQuantity);
						}else{
							hasInMap.put(keyStr, hsQuantity.add(hasInMap.get(keyStr)));
						}
					}
				}
				for(LogicPurchaseItemDO pcsItem : pcsmList){
					if(pcsItem==null){
						continue;
					}
					String keyStr = pcsItem.getZd002MaterId()+"_"+pcsItem.getZd006Model()+"_"
							+pcsItem.getZd023Size()+"_"+pcsItem.getZd021Color()+"_"
							+pcsItem.getZd022Quality();
					LogicPurchaseWareItemDO pcswm = new LogicPurchaseWareItemDO();
					pcswm.setZd003MaterId(pcsItem.getZd002MaterId());
					pcswm.setZd004Code(pcsItem.getZd003Code());
					pcswm.setZd005Name(pcsItem.getZd004Name());
					pcswm.setZd005Type(pcsItem.getZd005Type());
					pcswm.setZd006Spec(pcsItem.getZd005Spec());
					pcswm.setZd007Model(pcsItem.getZd006Model());
					pcswm.setZd009Color(pcsItem.getZd021Color());
					pcswm.setZd011Size(pcsItem.getZd023Size());
					pcswm.setZd010Quality(pcsItem.getZd022Quality());
					pcswm.setZd012Unit(pcsItem.getZd009Unit());
					pcswm.setZd016Price(pcsItem.getZd012Price());
					pcswm.setZd017TaxPrice(pcsItem.getZd013TaxPrice());
					pcswm.setZd014Quatity(pcsItem.getZd011Quatity());//订单数量
					pcswm.setZd024Descript(pcsItem.getZd025Descript());
					//已入库数量
					if(hasInMap.get(keyStr)==null){
						pcswm.setZd022InQuantity(BigDecimal.ZERO);
					}else{
						pcswm.setZd022InQuantity(hasInMap.get(keyStr));
					}
					pcswmList.add(pcswm);
				}
				OutJsonGrid out = new OutJsonGrid(pcswmList);
				out.printJSon(response);
			}
		}
	}
}
